<template>
  <div v-loading="loading">
    <div
      v-for="(item) in tagsData"
      :key="item.id"
      class="mb20"
    >
      <div v-if="item['cacheList'] && item['cacheList'].length > 0">
        <div class="area-header">
          <span class="area-header-title">{{ item.name }}</span>
          <i v-if="!item.show" class="el-icon-search link-type" @click="onSearch(item)" />
          <el-input
            v-if="item.show"
            v-model="item.searchVal"
            placeholder="请输入内容"
            prefix-icon="el-icon-search"
            size="mini"
            style="width:150px;"
            @input="onInput($event, item)"
          />

        </div>
        <div v-if="item['tagsTreeList'] && item['tagsTreeList'].length > 0">
          <el-radio-group v-model="item.tagsSelect0" :max="1" size="mini" class="radio-tag mb20" @change="tagFirstChange($event, item)">
            <el-radio-button v-for="tag in item['tagsTreeList']" :key="tag.id" sclass="mr10" :label="tag.id">
              {{ tag.name }}
            </el-radio-button>
          </el-radio-group>
        </div>
        <div v-else class="noTag">{{ $t('暂无标签') }}</div>
        <template v-for="v in 20">
          <!-- {{ v }} -->
          <div v-if="item['tagsTreeList'+ v] && item['tagsTreeList'+ v].length > 0" :key="v">
            <el-divider />
            <el-radio-group v-model="item['tagsSelect'+ v]" :max="1" size="mini" class="radio-tag mb20" @change="tagFirstChange($event, item, v)">
              <el-radio-button v-for="tag in item['tagsTreeList'+ v]" :key="tag.id" sclass="mr10" :label="tag.id">
                {{ tag.name }}
              </el-radio-button>
            </el-radio-group>
          </div>
        </template>

        <div class="genLabel">
          <span class="span">生成标签：</span>
          <div class="tagView">
            <el-tag
              v-for="v in item.vals"
              :key="v.id"
              closable
              size="mini"
              :disable-transitions="false"
              effect="plain"
              class="plainLabel"
              @close="handleClose(v.id, item)"
            >
              {{ v.name }}
            </el-tag>
            <span v-if="item.tagContent && item.tagContent.length > 1" class="cacheLabel">
              <template v-for="(ele, j) in item.tagContent">{{ j === 0 ? '' : '/' }}{{ ele.name }}</template>
              <i class="el-icon-check" @click="onCreate(item)" />
            </span>
          </div>
        </div>
      </div>
      <el-input
        v-if="item.tagInputVisible"
        ref="saveTagInput"
        v-model="item.firstLabel"
        class="input-new-tag"
        size="small"
        :placeholder="$t('请输入')"
        @keyup.enter.native="tagContentInput(item)"
        @blur="tagContentInput(item)"
      />
    </div>
  </div>
</template>

<script>
import { findConfigureAndTagsInfo } from '@/api/deal/tags/dealTagsConfigure'
import { saveMultipleList } from '@/api/deal/tags/dealTagsRef'
import { getDealType } from '@/api/base/deal/dealBase'
export default {
  name: 'TagSelect',
  props: {
    chosenTagData: {
      type: Array,
      default: undefined
    },
    tagsBusData: {
      type: Array,
      default: undefined
    },
    otherType: {
      type: String,
      default: undefined
    },
    busId: {
      type: String,
      default: undefined,
      description: '项目ID或者时投资组合ID'
    },
    busType: {
      type: String,
      default: undefined,
      description: '项目类型'
    }
  },
  data() {
    return {
      loading: false,
      tagsData: [],
      dealId: this.$route.query.id || this.busId,
      formArray: [],
      tagInputVisible: false,
      tagInputValue: undefined,
      dealType: this.$route.query.dealType || this.busType
    }
  },
  watch: {
    'chosenTagData': {
      handler(newVal) {
        this.loading = true
        if (newVal && newVal.length > 0) {
          console.log('标签页面tagsBusData', this.tagsBusData)
          if (this.tagsBusData && this.tagsBusData.length > 0) {
            this.tagsData = this.tagsBusData
            if (this.tagsData.length > 0) {
              this.tagsData.forEach(tag => {
                this.$set(tag, 'cacheList', JSON.parse(JSON.stringify(tag.tagsTreeList)))
                this.$set(tag, 'show', false)
                this.$set(tag, 'searchVal', '')
              })
            }
            this.loading = false
          } else {
            getDealType(this.dealId).then(res => {
              console.log('根据dealId获取dealType-1111111', res.data)
              // 如果根据项目ID获取不到项目类型，则使用传入的项目类型
              const dealType = res.data || this.busType
              findConfigureAndTagsInfo(dealType, this.busId).then(response => {
                this.tagsData = response.data
                if (this.tagsData.length > 0) {
                  this.tagsData.forEach(tag => {
                    this.$set(tag, 'cacheList', JSON.parse(JSON.stringify(tag.tagsTreeList)))
                    this.$set(tag, 'show', false)
                    this.$set(tag, 'searchVal', '')
                  })
                }
                this.loading = false
              })
            })
          }
        } else {
          getDealType(this.dealId).then(res => {
            console.log('根据dealId获取dealType', res.data)
            // 如果根据项目ID获取不到项目类型，则使用传入的项目类型
            const dealType = res.data || this.dealType
            findConfigureAndTagsInfo(dealType, this.busId).then(response => {
              this.tagsData = response.data
              if (this.tagsData.length > 0) {
                this.tagsData.forEach(tag => {
                  this.$set(tag, 'cacheList', JSON.parse(JSON.stringify(tag.tagsTreeList)))
                  this.$set(tag, 'show', false)
                  this.$set(tag, 'searchVal', '')
                })
              }
              this.loading = false
            })
          })
        }
      },
      deep: true,
      immediate: true
    }
  },
  created() {
  },
  mounted() {
  },
  methods: {
    loadTagsData() {
    },
    onInput(val, data) {
      // console.log(val, data)
      if (val === '') {
        data.tagsTreeList = data.cacheList
        for (let i = 0; i <= 5; i++) {
          this.$set(data, 'tagsSelect' + i, '')
          if (i > 0) {
            this.$set(data, 'tagsTreeList' + i, [])
          }
        }
      } else {
        data.tagsTreeList = data.cacheList.filter((item) => item.name.toString().indexOf(val) >= 0)
        for (let j = 0; j <= 5; j++) {
          this.$set(data, 'tagsSelect' + j, '')
          if (j > 0) {
            this.$set(data, 'tagsTreeList' + j, [])
          }
        }
      }
      this.$forceUpdate()
    },
    onSearch(data) {
      data.show = true
      data.searchVal = ''
    },
    // 关闭form页面
    cancel() {
      this.$emit('close')
    },
    tagFirstChange(val, item, index) {
      var _index = index || 1
      // console.log(val, index, _index)
      if (!index) { // 一级标签
        item.tagsTreeList && item.tagsTreeList.forEach(v => {
          if (v && v.hasChildren === false && v.id === val) {
            var row = {
              name: v.name,
              id: v.id
            }
            item.vals.push(row)
            this.$set(item, 'tagsSelect0', '')
            this.$set(item, 'tagsTreeList1', [])
            item.tagContent = []
          }
          if (v && v.hasChildren === true && v.id === val) {
            this.$set(item, 'tagsTreeList' + _index, v.children)
            this.$set(item, 'tagsSelect' + _index, '')
            item.tagContent = [{
              name: v.name,
              id: v.id
            }]
          }
          var ind = _index
          this.$set(item, 'tagsSelect' + ind, '')
          if (item.tagContent) {
            item.tagContent.splice(ind, 1)
          }
          ind++
          for (let i = ind; i <= 5; i++) {
            this.$set(item, 'tagsSelect' + i, '')
            this.$set(item, 'tagsTreeList' + i, [])
            if (item.tagContent) {
              item.tagContent.splice(ind, 1)
            }
          }
        })
      }
      if (index) {
        if (item['tagsSelect0'] === '') {
          for (let i = 1; i <= 5; i++) {
            this.$set(item, 'tagsSelect' + i, '')
          }
          return
        }
        // debugger
        var _child = this.findList(item['tagsTreeList' + _index], val)
        console.log(_child)
        if (_child) {
          item.tagContent[_index] = {
            name: _child.name,
            id: _child.id
          }
        }
        if (_child) {
          var ind = _index
          ind++
          if (_child.hasChildren === true) {
            this.$set(item, 'tagsTreeList' + ind, _child.children)
            this.$set(item, 'tagsSelect' + ind, '')
          } else {
            this.$set(item, 'tagsTreeList' + ind, [])
          }
          if (item.tagContent) {
            item.tagContent.splice(ind, 1)
          }
        }
      }
      this.$forceUpdate()
      // const map = new Map()
      // item.vals = item.vals.filter(key => !map.has(key.id) && map.set(key.id, 1))
      // item.tagContent = item.tagContent.filter(key => !map.has(key.id) && map.set(key.id, 1))
    },
    findList(list, id) {
      for (let i = 0; i < list.length; i++) {
        const item = list[i]
        if (item.id === id) {
          return item
        }
        if (item.children) {
          const child = this.findList(item.children, id)
          if (child) {
              return child
          }
        }
      }
    },
    /** 提交按钮 */
    submitForm() {
      // 点击保存时，把临时选中，并没有手动勾选确定的，也添加到保存中
      this.tagsData.forEach(item => {
        if (item.tagContent && item.tagContent.length > 1) {
          this.onCreate(item)
        }
      })
      saveMultipleList({ dealId: this.dealId, list: this.tagsData }).then(response => {
        if (response.code === 200) {
          this.msgSuccess(this.$t('保存成功'))
          this.$emit('close', true)
        } else {
          this.msgError(response.msg)
        }
        this.loading = false
      })
    },
    /** 父组件提交引用当前组件 , 提交时将当前选中的数据 传到父组件的方法内 */
    submitFormOut() {
      this.formArray = []
      this.tagsData.forEach(item => {
        // 只有大于0，意味着当前赛道有标签生成了
        if (item.vals.length > 0) {
          item.vals.forEach(v => {
            const tagRef = {
              id: undefined,
              dealId: this.dealId,
              configureId: item.id,
              configureLabel: item.name,
              firstTagId: undefined,
              firstTagLabel: undefined,
              firstEdit: undefined,
              secondTagId: undefined,
              secondTagLabel: undefined,
              thirdTagId: undefined,
              thirdTagLabel: undefined,
              fourthTagLabel: undefined,
              fourthTagId: undefined,
              fifthTagId: undefined,
              fifthTagLabel: undefined,
              tagContent: v.name
            }
            const idArray = v.id.split('/', 5)
            const nameArray = v.name.split('/', 5)
            const length = idArray.length
            switch (length) {
              case 1:
                tagRef.firstTagId = idArray[0]
                tagRef.firstTagLabel = nameArray[0]
                break
              case 2:
                tagRef.firstTagId = idArray[0]
                tagRef.firstTagLabel = nameArray[0]
                tagRef.secondTagId = idArray[1]
                tagRef.secondTagLabel = nameArray[1]
                break
              case 3:
                tagRef.firstTagId = idArray[0]
                tagRef.firstTagLabel = nameArray[0]
                tagRef.secondTagId = idArray[1]
                tagRef.secondTagLabel = nameArray[1]
                tagRef.thirdTagId = idArray[2]
                tagRef.thirdTagLabel = nameArray[2]
                break
              case 4:
                tagRef.firstTagId = idArray[0]
                tagRef.firstTagLabel = nameArray[0]
                tagRef.secondTagId = idArray[1]
                tagRef.secondTagLabel = nameArray[1]
                tagRef.thirdTagId = idArray[2]
                tagRef.thirdTagLabel = nameArray[2]
                tagRef.fourthTagId = idArray[3]
                tagRef.fourthTagLabel = nameArray[3]
                break
              case 5:
                tagRef.firstTagId = idArray[0]
                tagRef.firstTagLabel = nameArray[0]
                tagRef.secondTagId = idArray[1]
                tagRef.secondTagLabel = nameArray[1]
                tagRef.thirdTagId = idArray[2]
                tagRef.thirdTagLabel = nameArray[2]
                tagRef.fourthTagId = idArray[3]
                tagRef.fourthTagLabel = nameArray[3]
                tagRef.fifthTagId = idArray[4]
                tagRef.fifthTagLabel = nameArray[4]
                break
            }
            this.formArray.push(tagRef)
          })
        }
      })
      var data = {
        formArray: this.formArray,
        tagsBusData: this.tagsData
      }
      if (this.formArray.length === 0) {
        this.msgWarning(this.$t('请至少选择一个标签!'))
      } else {
        this.$emit('submitTag', data)
      }
    },

    tagContentInput(item) {
      item.tagInputVisible = false
      item.tagContent = item.firstLabel
    },
    handleClose(id, item) {
      var index = item.vals.findIndex(v => v.id === id)
      if (index !== -1) {
        item.vals.splice(index, 1)
      }
    },
    onCreate(item) {
      console.log(item)
      if (item.tagContent && item.tagContent.length > 0) {
        var names = ''
        var ids = ''
        item.tagContent.forEach((v, i) => {
          if (i === 0) {
            names += v.name
            ids += v.id
          } else {
            names += '/' + v.name
            ids += '/' + v.id
          }
        })
        // console.log(names, ids)
        item.vals.push({
          id: ids,
          name: names
        })
        item.tagContent = []
        // 点击确定按钮后取消选中标签的高亮
        for (let i = 0; i < 5; i++) {
          this.$set(item, 'tagsSelect' + i, '')
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.el-divider--horizontal {
    margin: 0 0 15px;
}
.input-new-tag {
  width: 200px;
  margin-left: 10px;
}
.radio-tag /deep/ .el-radio-button {
  margin-right: 10px;
  margin-top: 10px;
}
.radio-tag /deep/ .el-radio-button__inner {
  border: 1px solid #DCDFE6;
  border-radius: 4px;
  box-shadow: 0 0 0 0 #74bcff;
}

.genLabel{
  background: #f8f8f8;
  padding: 10px;
  display: flex;
  align-items: center;
  .span{
    white-space: nowrap;
  }
  .tagView{

  }
}
.plainLabel{
  margin: 3px;
}
.cacheLabel{
  height: 20px;
  padding: 0 5px;
  line-height: 19px;
  margin: 3px;
  font-size: 12px;
  border-radius: 4px;
  box-sizing: border-box;
  white-space: nowrap;
  border: 1px dashed #fbc4c4;
  color: #f56c6c;
  background: #fff;
  i{
    cursor: pointer;
    color: #f56c6c;
  }
}
.noTag{
  font-size: 13px;
  color: #b8b8b8;
  padding: 15px 0;
  margin-bottom: 10px;
  text-align: center;
  border: 1px solid #ececec;
}
/deep/.radio-tag{
  .el-radio-button__inner{
    transition: unset!important;
  }
}
</style>
